<?php

/**
 *
 * Upload asset to the server from andriod phone
 * @param	string	mode of the upload eg; new or replace
 *
 */
$mode = "insert";
function upload_asset($mode) {
	// Below lines are to display file name, temp name and file type , you can use them for testing your script only//////
	//echo "File Name: ".$_FILES[flUserfile][name]."<br>";
	//echo "tmp name: ".$_FILES[flUserfile][tmp_name]."<br>";
	//echo "File Type: ".$_FILES[flUserfile][type]."<br>";
	//echo "<pre>";
	//print_r($_FILES);
	//echo "</pre>";
	$resType = explode("/",$_FILES[flUserfile][type]);
	$sessionID = sprintf("%.12d",microtime(true));
	$resName = $sessionID."_".$_FILES[flUserfile][name];
	$resFullPath="assets/".$resType[0]."/".$resName; // the path with the file name where the file will be stored, upload is the directory name.

	if(move_uploaded_file ($_FILES[flUserfile][tmp_name],$resFullPath)){
		global $wpdb;
		global $current_user;
		$RES_ID = 0;
		$assetTable = $wpdb->prefix."asset";
		$assetKeywordTable = $wpdb->prefix."assetkeywords";
		if($mode == "insert") {
			$insertAssetSchema = "INSERT INTO $assetTable(RES_NAME, RES_TITLE, RES_PATH, RES_TYPE, IS_DELETED, CONTRIBUTOR_ID, PROJECT_ID, DESCRIPTION)
        	VALUES('$resName', '$_POST[txtTitle]','$resFullPath', '$resType[0]', '0', $current_user->ID, 1, '$_POST[txtAssetDescription]')";
			//echo $insertSchema;
			$wpdb->query($insertAssetSchema);
			$RES_ID = mysql_insert_id();

				
			if(isset($_POST[ldbSynAssetKeywords]) && ($_POST[ldbSynAssetKeywords]!="")) {
				for ($g=0; $g<sizeof($_POST[ldbSynAssetKeywords]); $g++) {
					$KEY_ID = $_POST[ldbSynAssetKeywords][$g];
					$insertAssetKeyword = "INSERT INTO $assetKeywordTable(RES_ID, KEY_ID) VALUES($RES_ID, $KEY_ID)";
					$wpdb->query($insertAssetKeyword);
				}
			}
		}
		else if($mode == "update") {
			$updateSchema = "UPDATE $table SET RES_NAME='$resName', RES_TITLE='$_POST[txtTitle]', RES_PATH='$resFullPath', RES_TYPE='$resType[0]', RES_DESCRIPTION='$_POST[txtAssetDescription]'
			WHERE RES_ID = $_POST[hdResID]";
			$wpdb->query($updateSchema);
			$wpdb->query("DELETE FROM $assetKeywordTable WHERE RES_ID=$_POST[hdResID]");
			if(isset($_POST[ldbSynAssetKeywords]) && ($_POST[ldbSynAssetKeywords]!="")) {
				for ($g=0; $g<sizeof($_POST[ldbSynAssetKeywords]); $g++) {
					$KEY_ID = $_POST[ldbSynAssetKeywords][$g];
					$insertAssetKeyword = "INSERT INTO $assetKeywordTable(RES_ID, KEY_ID) VALUES($_POST[hdResID], $KEY_ID)";
					$wpdb->query($insertAssetKeyword);
				}
			}
		}
		generate_thumbnail($resFullPath, $resName);
		//chmod("$add",0777);
	}
	else{
		?>
<script type="text/javascript">
		alert("Failed to upload file Contact Site admin to fix the problem");
		</script>
		<?php
		exit;
	}
}


/**
 *
 * Generate thumbnail for images and videos
 * @param	string resource relative path
 * @param	string resiurce name
 *
 */
function generate_thumbnail($resFullPath, $resName) {
	///////// Start the thumbnail generation//////////////
	$n_width=75; // Fix the width of the thumb nail images
	$n_height=75; // Fix the height of the thumb nail imaage

	$tsrc="assets/thumbnail/".$resName; // Path where thumb nail image will be stored
	$ggg =  $_FILES[flUserfile][type];
	//echo $ggg;
	/*
	 if (!($_FILES[userfile][type] =="image/jpeg" OR $_FILES[userfile][type]=="image/gif")){
		echo "Your uploaded file must be of JPG or GIF. Other file types are not allowed<BR>";
		exit;
		}
		*/
	//////////// Starting of GIF thumb nail creation///////////
	if (@strtoupper($_FILES[flUserfile][type])=="IMAGE/GIF") {
		$im=ImageCreateFromGIF($resFullPath);
		$width=ImageSx($im); // Original picture width is stored
		$height=ImageSy($im); // Original picture height is stored
		$newImage=imagecreatetruecolor($n_width,$n_height);
		imageCopyResized($newImage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
		if (function_exists("imagegif")) {
			Header("Content-type: image/gif");
			ImageGIF($newImage,$tsrc);
		}
		elseif (function_exists("imagejpeg")) {
			Header("Content-type: image/jpeg");
			ImageJPE($newImage,$tsrc);
		}
		//chmod("$tsrc",0777);
	}
	////////// end of gif file thumb nail creation//////////

	////////////// starting of JPG thumb nail creation//////////
	if(strtoupper($_FILES[flUserfile][type])=="IMAGE/JPEG"){
		$im=ImageCreateFromJPEG($resFullPath);
		$width=ImageSx($im); // Original picture width is stored
		$height=ImageSy($im); // Original picture height is stored
		$newImage=imagecreatetruecolor($n_width,$n_height);
		imageCopyResized($newImage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
		ImageJpeg($newImage,$tsrc);
		//chmod("$tsrc",0777);
	}

	if(strtoupper($_FILES[flUserfile][type])=="IMAGE/PNG"){
		$im=imagecreatefrompng($resFullPath);
		$width=ImageSx($im); // Original picture width is stored
		$height=ImageSy($im); // Original picture height is stored
		$newImage=imagecreatetruecolor($n_width,$n_height);
		imageCopyResized($newImage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
		imagepng($newImage,$tsrc);
		//chmod("$tsrc",0777);
	}

	if(strlen(strpos(strtoupper($_FILES[flUserfile][type]), "VIDEO"))>0) {
		echo "<script type='text/javascript'>";
		//echo "alert(getcwd())";
		echo "</script>";

		// movie.avi.... name of the movie you want to take a screenshot from
		// 00:00:00.... Where in the movie do you wanna take your screenshot, 10 seconds from start? ex: 00:00:10
		// picname..... name your generated pic
		//echo "video file done";
		$inputPath = getcwd()."\\assets\\video\\";
		$outputPath = getcwd()."\\assets\\thumbnail\\";
		$arrFileComp = explode(".", $resName);
		$fileName = "";
		for($index=0; $index<sizeof($arrFileComp)-1; $index++) {
			$fileName .= $arrFileComp[$index];
		}
		$inputVideoName = $inputPath.$resName;
		$thumbnailName = $outputPath.$fileName.".png";
		//echo $inputVideoName."********************".$thumbnailName."<br/>";
		convertToFlv($inputVideoName, $thumbnailName);
		//exec("START c:\ffmpeg\bin\ffmpeg -vcodec png -i C:\wamp\www\wordpress\assets\video\__Coca_Cola_mix1.mpeg -ss  00:00:03 -vframes frames test1%d.png");

	}
	////////// end of jpeg file thumb nail creation//////////
}



function convertToFlv($input, $output) {
	$pathToFfmpeg = "c:\\ffmpeg\\bin\\";
	//$shell = new COM("WScript.Shell") or die("Requires Windows Scripting Host");
	//$devenvpath=$shell->RegRead("HKEY_CLASSES_ROOT\\Local Settings\\SOFTWARE\\Microsoft\\Windows\\shell\\muicache\\");
	// echo "Converting $input to $output<br />";
	$command = $pathToFfmpeg."ffmpeg -v 0 -y -i $input -vframes 1 -ss 2 -vcodec mjpeg -f rawvideo -s 75x75 -aspect 16:9 $output ";
	// echo "$command<br />";
	shell_exec( $command );
	// echo "Converted<br />";
}


function validate_password($userName, $password) {
	global $wpdb;
	if(user_pass_ok($userName, $password)) {
		$userTable = $wpdb->prefix."users";
		$userID = "";
		$myrows = $wpdb->get_results("SELECT ID FROM $userTable WHERE user_login = $userName AND user_status = 0");
		foreach ($myrows as $myrow) {
			$userID = $myrow->ID;
		}
	}
	return $userID;
}

/**
 *
 * Get projects belongs to an user
 * @return	resultset  result set of projects
 *
 */
function get_projects_by_contributor($contributorID) {
	global $wpdb;
	$projContTable = $wpdb->prefix."projectcontributors";
	$projTable = $wpdb->prefix."projects";
	$myrows = $wpdb->get_results("SELECT DISTINCT $projTable.PROJ_ID, $projTable.PROJ_NAME, $projTable.PROJ_INFO
	FROM $projTable, $projContTable WHERE $projContTable.PROJ_ID = $projTable.PROJ_ID
	AND $projContTable.CONTRIBUTOR_ID = $contributorID ORDER BY $projTable.PROJ_DATE DESC");	
	return $myrows;
}
?>